import torch
import torch.nn as nn


class Encoder(nn.Module):
    def __init__(self):
        super().__init__()
        # 输入尺寸: [batch, 3, 64, 64]
        self.conv1 = nn.Conv2d(3, 32, kernel_size=3, stride=2, padding=1)  # 输出: [32, 32, 32]
        self.bn1 = nn.BatchNorm2d(32)
        self.conv2 = nn.Conv2d(32, 64, kernel_size=3, stride=2, padding=1)  # 输出: [64, 16, 16]
        self.bn2 = nn.BatchNorm2d(64)
        self.conv3 = nn.Conv2d(64, 128, kernel_size=3, stride=2, padding=1)  # 输出: [128, 8, 8]
        self.bn3 = nn.BatchNorm2d(128)
        self.conv4 = nn.Conv2d(128, 256, kernel_size=3, stride=2, padding=1)  # 输出: [256, 4, 4]
        self.bn4 = nn.BatchNorm2d(256)
        self.relu = nn.ReLU(inplace=True)

    def forward(self, x):
        x = self.relu(self.bn1(self.conv1(x)))
        x = self.relu(self.bn2(self.conv2(x)))
        x = self.relu(self.bn3(self.conv3(x)))
        x = self.relu(self.bn4(self.conv4(x)))
        return x  # 输出特征图: [256, 4, 4]


class Decoder(nn.Module):
    def __init__(self):
        super().__init__()
        # 输入尺寸: [256, 4, 4]
        self.tconv1 = nn.ConvTranspose2d(256, 128, kernel_size=3, stride=2, padding=1,
                                         output_padding=1)  # 输出: [128, 8, 8]
        self.bn1 = nn.BatchNorm2d(128)
        self.tconv2 = nn.ConvTranspose2d(128, 64, kernel_size=3, stride=2, padding=1,
                                         output_padding=1)  # 输出: [64, 16, 16]
        self.bn2 = nn.BatchNorm2d(64)
        self.tconv3 = nn.ConvTranspose2d(64, 32, kernel_size=3, stride=2, padding=1,
                                         output_padding=1)  # 输出: [32, 32, 32]
        self.bn3 = nn.BatchNorm2d(32)
        self.tconv4 = nn.ConvTranspose2d(32, 3, kernel_size=3, stride=2, padding=1, output_padding=1)  # 输出: [3, 64, 64]
        self.relu = nn.ReLU(inplace=True)
        self.sigmoid = nn.Sigmoid()

    def forward(self, x):
        x = self.relu(self.bn1(self.tconv1(x)))
        x = self.relu(self.bn2(self.tconv2(x)))
        x = self.relu(self.bn3(self.tconv3(x)))
        x = self.tconv4(x)  # 不使用BN和ReLU
        x = self.sigmoid(x)  # 将输出压缩到[0,1]范围
        return x


class CAE(nn.Module):
    def __init__(self):
        super().__init__()
        self.encoder = Encoder()
        self.decoder = Decoder()

    def forward(self, x):
        latent = self.encoder(x)  # 提取特征
        reconstructed = self.decoder(latent)  # 重建图像
        return reconstructed

    def save(self, path):
        torch.save(self.encoder, path)


# 测试网络
if __name__ == "__main__":
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    model = CAE().to(device)

    # 创建随机输入数据 (batch_size=4, 3通道, 64x64)
    input_tensor = torch.randn(4, 3, 64, 64).to(device)

    # 前向传播
    output = model(input_tensor)

    print("输入尺寸:", input_tensor.size())
    print("输出尺寸:", output.size())
    print("编码特征尺寸:", model.encoder(input_tensor).size())